package com.iye.puretennis.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.*;
import com.iye.puretennis.LoginActivity;
import com.iye.puretennis.R;
import com.iye.puretennis.custom.BaseActivity;
import com.iye.puretennis.custom.UploadImagePopupWindow;
import com.iye.puretennis.domain.*;
import com.iye.puretennis.helper.Constant;
import com.iye.puretennis.helper.ImageHelper;
import com.iye.puretennis.helper.RemoteUrlCollections;
import com.iye.puretennis.helper.ServerAccessHelper;
import com.iye.puretennis.utils.ImageUtils;
import com.iye.puretennis.utils.JsonUtils;
import com.iye.puretennis.utils.StringUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.utils.DiskCacheUtils;
import com.nostra13.universalimageloader.utils.MemoryCacheUtils;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Author: Chuanbao on 2014/11/20.
 */
public class ProfileActivity extends BaseActivity {
    private RadioGroup genderRadioGroup;
    private RadioButton femaleRadio;
    private RadioButton maleRadio;
    private ImageView uploadImageView;

    private List<Idol> idols = new ArrayList<Idol>();
    private Profile profile;
    private boolean renderProfileOthers = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.profile);
        EditText nickNameText = (EditText) findViewById(R.id.nickname);
        nickNameText.setTypeface(defaultTypeface);

        genderRadioGroup = (RadioGroup) findViewById(R.id.profile_gender_group);
        femaleRadio = (RadioButton) findViewById(R.id.profile_gender_female);
        maleRadio = (RadioButton) findViewById(R.id.profile_gender_male);

        uploadImageView = (ImageView) findViewById(R.id.profile_image_view);

        int layout = height / 3;

        ViewGroup.LayoutParams layoutParams = uploadImageView.getLayoutParams();

        layoutParams.width = layout;

        layoutParams.height = layout;

        uploadImageView.setLayoutParams(layoutParams);

        uploadImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int vid = v.getId();
                if (vid == uploadImageView.getId()) {
                    showPopUp();
                }
            }
        });

        ImageButton backButton = (ImageButton) findViewById(R.id.back_button);
        if(token.isSetup()){
            backButton.setVisibility(View.VISIBLE);
        }else{
            backButton.setVisibility(View.GONE);
        }

        Intent intent = getIntent();
        profile = new Profile();
        profile.setGuid(intent.getStringExtra("guid"));


        String profileCache = dbManager.retrieveMyCachedData(CacheType.MY_PROFILE.name());
        String idolsCache = dbManager.retrieveMyCachedData(CacheType.IDOLS.name());
        if (StringUtils.hasText(profileCache)) {
            profile = JsonUtils.toProfile(profileCache);
            idols = convertJsonToIdols(idolsCache);
            renderProfile(profile);
            renderProfileOthers = true;
        } else {
            renderProfileOthers = false;
        }


        //render page
        final String userToken = token.getToken();
        new Thread(new Runnable() {
            @Override
            public void run() {
                profile = loadProfile(token.getGuid(), userToken);
                idols = loadIdols(userToken);
                runOnUiThread(uiProfileUpdate);
            }
        }).start();


    }

    private Runnable uiProfileUpdate = new Runnable() {
        @Override
        public void run() {
            if (profile != null) {

                renderProfile(profile);

            }
        }
    };

    //update the check -  unChecked icon
    private void handleGenderIcon(RadioButton femaleRadioButton, RadioButton maleRadioButton, boolean maleChecked) {

        if (maleChecked) {
            Drawable maleRadioChecked = getResources().getDrawable(R.drawable.male_checked);
            maleRadioChecked.setBounds(0, 0, maleRadioChecked.getMinimumWidth(), maleRadioChecked.getMinimumHeight());
            maleRadioButton.setCompoundDrawables(maleRadioChecked, null, null, null);

            Drawable femalRadioUnChecked = getResources().getDrawable(R.drawable.female_unchecked);
            femalRadioUnChecked.setBounds(0, 0, femalRadioUnChecked.getMinimumWidth(), femalRadioUnChecked.getMinimumHeight());
            femaleRadioButton.setCompoundDrawables(femalRadioUnChecked, null, null, null);
        } else {
            Drawable femaleRadioChecked = getResources().getDrawable(R.drawable.female_checked);
            femaleRadioChecked.setBounds(0, 0, femaleRadioChecked.getMinimumWidth(), femaleRadioChecked.getMinimumHeight());
            femaleRadioButton.setCompoundDrawables(femaleRadioChecked, null, null, null);

            Drawable maleRadioUnChecked = getResources().getDrawable(R.drawable.male_unchecked);
            maleRadioUnChecked.setBounds(0, 0, maleRadioUnChecked.getMinimumWidth(), maleRadioUnChecked.getMinimumHeight());
            maleRadioButton.setCompoundDrawables(maleRadioUnChecked, null, null, null);
        }
    }


    private void renderProfile(Profile profile) {

        //nick name
        EditText nickNameView = (EditText) findViewById(R.id.nickname);
        Typeface face = Typeface.createFromAsset(getAssets(), Constant.DEFAULT_FONT);
        nickNameView.setTypeface(face);
        nickNameView.setText(profile.getName());


        //add radio group checked change listener
        genderRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                boolean maleChecked = (checkedId == maleRadio.getId());
                handleGenderIcon(femaleRadio, maleRadio, maleChecked);
            }
        });

        boolean equalsMale = Gender.MALE.name().equals(profile.getGender());
        genderRadioGroup.check(equalsMale ? maleRadio.getId() : femaleRadio.getId());
        handleGenderIcon(femaleRadio, maleRadio, equalsMale);

        //profile
        String profileGuid = profile.getGuid();
        DisplayImageOptions options = builder.extraForDownloader(profileGuid).cacheInMemory(true).cacheOnDisk(true).build();
        ImageLoader.getInstance().displayImage(ImageHelper.getImageUri(profileGuid), uploadImageView, options);

    }

    private int selectedSpinnerPosition(String myIdolGuid) {
        for (int i = 0; i < idols.size(); i++) {
            if (idols.get(i).getGuid().equals(myIdolGuid)) {
                return i;
            }
        }
        return 0;
    }

    /**
     * update the profile of the user
     *
     * @param view
     */
    public void updateProfile(View view) {
        EditText nickNameTag = (EditText) findViewById(R.id.nickname);
        final String nickname = nickNameTag.getText().toString();
        RadioButton genderBtn = (RadioButton) findViewById(genderRadioGroup.getCheckedRadioButtonId());
        String gender = Gender.FEMALE.name();
        if (maleRadio.getId() == genderBtn.getId()) {
            gender = Gender.MALE.name();
        }
        final String finalGender = gender;
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject profileJsonObj = new JSONObject();
                try {
                    profileJsonObj.put("guid", token.getGuid());
                    profileJsonObj.put("nickname", nickname);
                    profileJsonObj.put("gender", finalGender);
                    profileJsonObj.put("idolGuid", "");
                    profileJsonObj.put("imageBase64Byte", profile.getImageBase64Byte());
                    StringEntity paramEntity = new StringEntity(profileJsonObj.toString(), Constant.CHARSET_UTF8);
                    ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.PROFILE), token.getToken(), paramEntity);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            handleAfterSave();
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void updateProfileImage(final Bitmap bitmap) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject profileJsonObj = new JSONObject();
                try {
                    String bitmapToBase64 = ImageUtils.bitmapToBase64(bitmap);
                    profileJsonObj.put("base64Bytes", bitmapToBase64);
                    StringEntity paramEntity = new StringEntity(profileJsonObj.toString(), Constant.CHARSET_UTF8);
                    ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.PROFILE_IMAGE), token.getToken(), paramEntity);
                    profile.setImageBase64Byte(bitmapToBase64);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ImageLoader imageLoader = ImageLoader.getInstance();
                            String imageUri = ImageHelper.getImageUri(token.getGuid());
                            MemoryCacheUtils.removeFromCache(imageUri, imageLoader.getMemoryCache());
                            DiskCacheUtils.removeFromCache(imageUri, imageLoader.getDiskCache());
                            Toast.makeText(ProfileActivity.this, "头像更新成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void handleAfterSave() {
        Intent intent = new Intent(this, MainTabsActivity.class);
        intent.putExtra("tab", 3);
        startActivity(intent);
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 拍照或者读取相册缩放图片
        boolean pickPhoto = requestCode == Constant.PICK_PHOTO;
        boolean takePhoto = requestCode == Constant.TAKE_PHOTO;
        if (takePhoto || pickPhoto) {
            Intent intent = new Intent(Constant.SYSTEM_ACTIVITY_CROP);
            Uri uri = null;
            if (data != null) {
                uri = data.getData();
            } else if (takePhoto) {
                uri = Uri.fromFile(new File(UploadImagePopupWindow.FILE_PATH));
            }
            if (uri != null) {
                intent.setDataAndType(uri, Constant.IMAGE_UNSPECIFIED);

                intent.putExtra("crop", "true");
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("outputX", Constant.PROFILE_IMAGE_WIDTH);
                intent.putExtra("outputY", Constant.PROFILE_IMAGE_HEIGHT);
                intent.putExtra("noFaceDetection", true);
                intent.putExtra("return-data", true);
                startActivityForResult(intent, Constant.CROP_PHOTO);
            }
        }

        if (requestCode == Constant.CROP_PHOTO && data != null) {
            handleProfileImage(data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void handleProfileImage(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap bitmap = extras.getParcelable("data");
            Bitmap compress = ImageUtils.compressImage(bitmap, 200);
            this.uploadImageView.setImageBitmap(compress);
            updateProfileImage(compress);
        }

    }

    /**
     * ***********************Remote server request part********************************
     */
    private List<Idol> loadIdols(String access_token) {
        List<Idol> idols = new ArrayList<Idol>();
        String result = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.IDOLS), access_token);
        if (!Constant.RESPONSE_BADLY.equals(result)) {
            String cacheType = CacheType.IDOLS.name();
            if (renderProfileOthers) {
                dbManager.updateMyCachedData(cacheType, result);
            } else {
                dbManager.cacheMyData(cacheType, result);
            }
            idols = convertJsonToIdols(result);
        }
        return idols;
    }

    private List<Idol> convertJsonToIdols(String result) {
        List<Idol> idols = new ArrayList<Idol>();
        try {
            JSONArray jsonArrays = new JSONArray(result);
            for (int i = 0; i < jsonArrays.length(); i++) {
                JSONObject jsonObj = jsonArrays.getJSONObject(i);
                String guid = jsonObj.getString("guid");
                String name = jsonObj.getString("name");
                idols.add(new Idol(guid, name));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return idols;
    }

    private Profile loadProfile(String userGuid, String access_token) {
        String result = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.PROFILE) + "/" + userGuid, access_token);
        if (!Constant.RESPONSE_BADLY.equals(result)) {
            String cacheType = CacheType.MY_PROFILE.name();
            if (renderProfileOthers) {
                dbManager.updateMyCachedData(cacheType, result);
            } else {
                dbManager.cacheMyData(cacheType, result);
            }
            return JsonUtils.toProfile(result);
        }
        return null;
    }


    private void showPopUp() {
        PopupWindow popupWindow = new UploadImagePopupWindow(this);
        popupWindow.showAtLocation(findViewById(R.id.profile), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void back(View view) {
        Intent intent = new Intent(this, MainTabsActivity.class);
        intent.putExtra("tab", 4);
        startActivity(intent);
    }


}